
import './CustomTable.scss'


import { useRequest } from 'alova'
import { useRef, useState, useEffect } from 'react'
import { Collapse, Spin, Result, Empty, Tag, Button } from "antd"
import { ProTable, TableDropdown } from '@ant-design/pro-components'
import { useDrag, useDrop, useEventEmitter, useLatest, useReactive } from 'ahooks'

import { Http } from '../../Api'
import { ModelBox } from '../../Model'
import { FormTemplate } from '../../Utils/FormTemp'
import { CustomTableColumns, CustomTableOptions } from './CustomTableConfig'
import { v4 } from 'uuid'

const SimulatedData = {
    user: [],
    engineeringOrganizations: [
        "uuid",
        "organizationName",
        "tableName",
        "fullName",
        "createUserUuid",
        "createUserName",
        "createTime",
        "updateUserUuid",
        "updateUserName",
        "updateTime",
        "isEnabled",
        "code",
        "keyword",
        "sortId",
        "parentUuid",
        "remark",
        "entityAttribute",
        "projectManager",
        "owner",
        "constructionSite",
        "numberLength",
        "qualifiedUnit",
        "cooperationType",
        "engineeringScale",
        "winningBidder",
        "construction",
        "contractStartDate",
        "contractEndDate",
        "acceptanceDate",
        "workStartDate",
        "workEndDate",
        "contractAmount",
        "acceptanceAmount",
        "isInsideEnterprise",
        "isTendering",
        "engineeringStatus",
        "isContractSigned",
        "embodyType",
        "organizationUuid",
        "address",
        "chaptersAmount",
        "projectManagementTeam",
        "provisionalAmount",
        "qualificationType",
        "engineeringType",
        "isEnabledCost",
        "isEnabledFinance",
        "constructionUuid",
        "winningBidderUuid"
    ]
}


// !!! 字段类型选择

const SetBaseTemp = ({ SetEvent }) => {
    const ConfigData = useReactive({ DataSheet: undefined, Controller: 'getTestJTGJ', params: 'pageSize=10', IsSearch: true, IsTitle: true })
    const ModalEvent = useEventEmitter()
    const ChangeEvent = useEventEmitter()
    const { send: getSheet } = useRequest(params => Http({ url: 'getCommonJsonInfoByUuid', params: { uuid: `sheet/${params}` } }), { immediate: false })
    const { send: posSheet } = useRequest(({ params, title }) => Http({ url: 'posCommonJsonInfoByUuid', params, path: [`sheet/${title}`] }), { immediate: false })
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'Added') {
            // console.log('覆盖原有sheet数据', val)
            ModalEvent.emit({ type: 'offLoading' })
            SetEvent.emit({ type: 'saveSheet', data })
            // posSheet({ params: JSON.stringify(JSON.stringify(val)), title: obj[uuid].title }).then(()=>console.log('保存成功->绑定数据信息'))
        }
    })
    ChangeEvent.useSubscription(val => {
        const { DataSheet } = val
        if (DataSheet && DataSheet !== ConfigData.DataSheet) {
            ConfigData.DataSheet = DataSheet
            SetEvent.emit({ type: 'loadTrue', data: '正在更换数据表...' })
            setTimeout(() => SetEvent.emit({ type: 'loadFalse' }), 100)
            // getSheet(DataSheet)
            //     .then(res => {
            //         console.log('请求成功', res)
            //     }).catch(res => {
            //         console.log('请求失败', res)
            //         setLoading(false)
            //     })
        }
    })
    return (
        <FormTemplate columns={CustomTableColumns} ModalEvent={ModalEvent} ChangeEvent={ChangeEvent} init={ConfigData} />
    )
}

const SetFieldTemp = ({ SetEvent }) => {
    const [SheetData, setSheetData] = useState()
    const [TableField, setTableField] = useState()
    const [Existing, setExisting] = useState(['uuid'])

    SetEvent.useSubscription(val => {
        const { type, data } = val
        switch (type) {
            case 'loadTrue':
                setSheetData()
                setTableField()
                break;
            case 'saveSheet':
                // SetEvent.emit({ type: 'loadTrue', data: '正在获取数据表字段...' })
                setTableField(SimulatedData[data.DataSheet])
                setSheetData(data)
                break;
            case 'existField':
                setExisting(data)
                break
            default:
                break;
        }
    })

    const TagTemp = ({ title }) => {
        const TagRef = useRef()
        useDrag(title, TagRef)
        if (Existing.includes(title)) return <Tag bordered={false} color="processing">{title}</Tag>
        else return <Tag bordered={false} ref={TagRef}>{title}</Tag>
    }


    return (
        <div className='SetFieldTemp'>
            {TableField ?
                TableField.length !== 0 ?
                    <div>
                        {TableField.map(key => <TagTemp key={key} title={key} />)}
                    </div> :
                    <Empty /> :
                <Result
                    status="warning"
                    title="请选择数据表"
                />
            }
        </div>
    )
}

const SetOptionTemp = ({ SetEvent }) => {
    const ConfigData = useReactive({})

    const ModalEvent = useEventEmitter()
    const ChangeEvent = useEventEmitter()

    // 操作设置
    return (
        <div className='SetOptionTemp'>
            {/* 基础操作项 */}
            {/* <div>新增</div>
            <div>修改</div>
            <div>删除</div> */}
            {/* 额外操作 */}
            {/* <div>更多组件  tableAll tableTd</div> */}

            <FormTemplate columns={CustomTableOptions} ModalEvent={ModalEvent} ChangeEvent={ChangeEvent} init={ConfigData} />
        </div>
    )
}

const SetMenuTemp = () => {
    return (
        <div>
            <div>内置菜单</div>
        </div>
    )
}

const ProTableTemp = ({ SetEvent }) => {
    const RightBox = useRef()
    const actionRef = useRef()
    const [Existing, setExisting] = useState(['uuid'])
    const [OptionsCall, setOptionsCall] = useState()
    const [Columns, setColumns] = useState([
        { dataIndex: 'uuid', valueType: 'Input', hideInTable: true, hideInSearch: true },
        {
            title: '操作',
            dataIndex: "systemOperation",
            valueType: 'systemOperation',
            fixed: 'right',
            width: 160,
            hideInSearch: true,
            hideInAdded: true,
            hideInModify: true,
            onHeaderCell: () => ({ onClick: () => ThClick('systemOperation') }),
            render: (_, record) => {
                return [
                    <Button type='link'>修改</Button>,
                    <Button type='link' danger>删除</Button>
                ]
            },
        },
    ])

    const ColumnsLast = useLatest(Columns)
    const Params = useReactive({ pageIndex: 1, pageSize: 10 })
    const [ConfigData, setConfigData] = useState()

    const { send: getData } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    SetEvent.useSubscription(val => {
        const { type, data } = val
        switch (type) {
            case 'saveSheet':
                const { params: obj } = data
                const params = Object.fromEntries(new URLSearchParams(obj))
                Object.keys(params).forEach(key => Params[key] = params[key])
                setConfigData(data)
                break;
            default:
                break;
        }
    })

    const ThClick = (e) => {

        if (e === 'systemOperation') {
            console.log('操纵设置')
        } else setOptionsCall({
            type: 'TableFieldConfig',
            title: e + ' 字段设置',
            width: 1000,
            data: { field: e, init: ColumnsLast.current.find(v => v.dataIndex === e) },
        })
    }

    useDrop(RightBox, {
        onDom: (e) => {
            const arr = [...Existing, e]
            setExisting(arr)
            setColumns(arr => ([
                ...arr,
                {
                    title: e,
                    dataIndex: e,
                    width: 160,
                    rules: false,
                    hideInTable: false,
                    hideInSearch: false,
                    hideInAdded: false,
                    hideInModify: false,
                    ellipsis: false,
                    copyable: false,
                    tooltip: '',
                    valueType: 'Input',
                    onHeaderCell: () => ({ onClick: () => ThClick(e) })
                }
            ]))
            SetEvent.emit({ type: 'existField', data: arr })
        }
    })
    const replaceObjectInArray = (array, newObj) => array.map(item => item.dataIndex === newObj.dataIndex ? newObj : item)
    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'modifyField') {
            const newData = { ...data, onHeaderCell: () => ({ onClick: () => ThClick(data.dataIndex) }) }
            const arr = replaceObjectInArray(Columns, newData)
            setColumns(arr)
            ModalEvent.emit({ type: 'TableFieldConfigOff' })
        }
    })

    const getTableData = async (data) => {
        const params = { ...data, ...Params }
        return getData({ url: ConfigData.Controller, params }).then(res => ({ data: res.list, total: res.total, success: true }))
    }

    useEffect(() => {
        console.log('列组合结果', Columns)
    }, [Columns])

    const onColumnsChange = e => {
        const sortedKeys = Object.keys(e)
            .sort((a, b) => {
                const orderA = e[a].order !== undefined ? e[a].order : Infinity;
                const orderB = e[b].order !== undefined ? e[b].order : Infinity;
                return orderA - orderB;
            });
        const indexMap = {}
        Columns.forEach((item, index) => { indexMap[item.dataIndex] = index })
        const reorderedArray = sortedKeys.map(dataIndex => Columns[indexMap[dataIndex]])
        setColumns(reorderedArray)
    }
    return (
        <div className='Right' ref={RightBox}>
            {ConfigData && Params &&
                <ProTable
                    actionRef={actionRef}
                    columns={Columns}
                    rowKey="uuid"
                    search={ConfigData.IsSearch}
                    request={getTableData}
                    params={Params}
                    options={{
                        fullScreen: true,
                        density: false,
                        setting: {
                            checkable: false,
                            checkedReset: false
                        }
                    }}
                    pagination={{
                        pageSize: Params.pageSize,
                        showSizeChanger: true,
                        onChange: (i, s) => {
                            Params.pageIndex = i
                            Params.pageSize = Number(s)
                        },
                    }}
                    headerTitle="表格名称"
                    scroll={{ x: 800, y: 600 }}
                    columnsState={{ onChange: onColumnsChange }}
                    toolBarRender={() => {

                        return [
                            // <Button key='Added' type='primary'>新增</Button>
                        ]
                    }}
                />
            }
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}



const CustomTable = () => {
    const [Loading, setLoading] = useState(false)
    const [LoadTip, setLoadTip] = useState('')
    const SetEvent = useEventEmitter()
    SetEvent.useSubscription(val => {
        const { type, data } = val
        switch (type) {
            case 'loadTrue':
                setLoadTip(data)
                setLoading(true)
                break;
            case 'loadFalse':
                setLoadTip('')
                setLoading(false)
                break
            default:
                break;
        }
    })

    const items = [
        { key: 1, label: '基础设置', children: <SetBaseTemp SetEvent={SetEvent} />, },
        { key: 2, label: '字段设置', children: <SetFieldTemp SetEvent={SetEvent} />, },
        // { key: 3, label: '操作设置', children: <SetOptionTemp SetEvent={SetEvent} />, },
        // { key: 4, label: '内置菜单', children: <SetMenuTemp SetEvent={SetEvent} />, collapsible: "disabled" },
    ]

    return (
        <div className='CustomTable'>
            <Spin spinning={Loading} tip={LoadTip}>
                <Collapse items={items} defaultActiveKey={[1, 2, 3]} />
                <ProTableTemp SetEvent={SetEvent} />
            </Spin>
        </div>
    );
};

export default CustomTable;